package com.blog.service.impl;

import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.blog.dao.MBlogMapper;
import com.blog.dao.MCategoryMapper;
import com.blog.dao.MUserMapper;
import com.blog.pojo.MBlog;
import com.blog.pojo.MBlogExample;
import com.blog.pojo.MCategory;
import com.blog.pojo.MCategoryExample;
import com.blog.pojo.MUser;
import com.blog.service.IBlogService;
import com.blog.vo.DetailVo;
import com.blog.vo.MBlogAndCategoryVo;
import com.blog.vo.MBlogVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontProvider;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;

@Service
public class BlogService implements IBlogService {

	@Autowired
	private MBlogMapper blogMapper;
	
	@Autowired
	private MCategoryMapper catMapper;
	
	@Autowired
	private MUserMapper userMapper;
	
	//增加 与 修改
	@Override
	public void save(MBlog blog) {
		
		
		if(blog.getId()!=null){

			//修改
			blog.setUpdated(blog.getCreated());
			blogMapper.updateByPrimaryKeyWithBLOBs(blog);
			
		}else{
			//添加
			blog.setUpdated(new Date());
			blogMapper.insert(blog);
		}
		
	}

	
	@Override
	public List<MBlogVo> selectAll() {
		
		MBlogExample example = new MBlogExample();
		
		List<MBlog> lists = blogMapper.selectByExample(example );
		
		List<MBlogVo> listVo = new ArrayList<>();
		
		
		for (MBlog mBlog : lists) {
		
			//遍历组装 blogVo
			MBlogVo vo = new MBlogVo();
			
			vo.setAuthor(mBlog.getAuthor());
			vo.setCategoryid(mBlog.getCategoryid());
			vo.setContent(mBlog.getContent());
			vo.setCreated(mBlog.getCreated());
			vo.setUpdated(mBlog.getUpdated());
			vo.setId(mBlog.getId());
			vo.setTitle(mBlog.getTitle());
			
			String name = catMapper.selectNameById(mBlog.getCategoryid());
			vo.setCategoryName(name);
			
			listVo.add(vo);
		}
		
		
		return listVo;
	}
	
	//添加分页
	@Override
	public PageInfo selectAllJson(Integer pageNum, Integer pageSize) {
		
		MBlogExample example = new MBlogExample();
		 
		
		//分页
		PageHelper.startPage(pageNum, pageSize);
		List<MBlog> lists = blogMapper.selectByExample(example );
		
		
		List<MBlogVo> listVo = new ArrayList<>();
		for (MBlog mBlog : lists) {
			
			//遍历组装 blogVo
			MBlogVo vo = new MBlogVo();
			
			vo.setAuthor(mBlog.getAuthor());
			vo.setCategoryid(mBlog.getCategoryid());
			vo.setContent(mBlog.getContent());
			vo.setCreated(mBlog.getCreated());
			vo.setUpdated(mBlog.getUpdated());
			vo.setId(mBlog.getId());
			vo.setTitle(mBlog.getTitle());
			
			String name = catMapper.selectNameById(mBlog.getCategoryid());
			vo.setCategoryName(name);
			
			listVo.add(vo);
		}
		
		PageInfo info = new PageInfo(lists);
		info.setList(listVo);
		
		return info;
	}


	@Override
	public MBlog selectById(Integer id) {
		
		MBlog blog = blogMapper.selectByPrimaryKey(id);
		return blog;
	}


	@Override
	public int delete(Integer id) {
		
		int res = blogMapper.deleteByPrimaryKey(id);
		return res;
	}


	@Override
	public List<MBlogVo> selectByName(String title) {
		
		title = "%"+title+"%";
		
		List<MBlog> lists = blogMapper.selectByName(title);
		
		if(lists == null){
			return null;
		}
		
		List<MBlogVo> listVo = createBlogListVo(lists);
		
		return listVo;
	}
	
	@Override
	public PageInfo selectByName2(String title, Integer pageNum, Integer pageSize) {
		
		title = "%"+title+"%";
		
		//分页
		PageHelper.startPage(pageNum, pageSize);
		List<MBlog> lists = blogMapper.selectByName(title);
		
		if(lists == null){
			return null;
		}
		
		List<MBlogVo> listVo = createBlogListVo(lists);
		
		PageInfo info = new PageInfo(lists);
		info.setList(listVo);
		
		return info;
	}

	
	//遍历 List<MBlog> 集合，将其重新组装为 List<MBlogVo>
	private List<MBlogVo> createBlogListVo(List<MBlog> blogList){
		
		List<MBlogVo> blogVoList = new ArrayList<>();
		
		for (MBlog mBlog : blogList) {
			
			//遍历组装 blogVo
			MBlogVo bvo = new MBlogVo();
			
			bvo.setId(mBlog.getId()); 
			bvo.setTitle(mBlog.getTitle());
			bvo.setAuthor(mBlog.getAuthor());
			bvo.setCategoryid(mBlog.getCategoryid());
			bvo.setContent(mBlog.getContent());
			bvo.setCreated(mBlog.getCreated());
			bvo.setUpdated(mBlog.getUpdated());
			
			String name = catMapper.selectNameById(mBlog.getCategoryid());
			bvo.setCategoryName(name);
			
			blogVoList.add(bvo); 
		}
		
		return blogVoList;
	}
	

	@Override
	public MBlogAndCategoryVo query2() {
		
		MBlogAndCategoryVo vo = new MBlogAndCategoryVo();
		
		//博客分类 
		MCategoryExample example2 = new MCategoryExample();
		
		List<MCategory> categoryList = catMapper.selectByExample(example2);
		vo.setCaterogyList(categoryList);
		
		//作者信息
		//       留作扩展， 现在定死id为1，只有一人
		MUser user = userMapper.selectByPrimaryKey(1);
		vo.setUser(user);
		
		 
		//博客具体内容
		MBlogExample example = new MBlogExample();
		example.setOrderByClause("updated desc");
		List<MBlog> blogList = blogMapper.selectByExampleWithBLOBs(example);
		
//		List<MBlogVo> blogVoList = new ArrayList<>();
//		for (MBlog mBlog : blogList) {
//		
//			//遍历组装 blogVo
//			MBlogVo bvo = new MBlogVo();
//			
//			bvo.setId(mBlog.getId()); 
//			bvo.setTitle(mBlog.getTitle());
//			bvo.setAuthor(mBlog.getAuthor());
//			bvo.setCategoryid(mBlog.getCategoryid());
//			bvo.setContent(mBlog.getContent());
//			bvo.setCreated(mBlog.getCreated());
//			bvo.setUpdated(mBlog.getUpdated());
//			
//			String name = catMapper.selectNameById(mBlog.getCategoryid());
//			bvo.setCategoryName(name);
//			
//			blogVoList.add(bvo); 
//		}
		
		List<MBlogVo> blogVoList = createBlogListVo(blogList);
		
		vo.setBlogVoList(blogVoList);
		
		return vo;
	}



	
	
	@Override
	public DetailVo getDetail(int id) {
		
		DetailVo detailVo = new DetailVo();
		
		MBlogVo blogVo = new MBlogVo();
		
		//设置博客详细内容
		MBlog blog = blogMapper.selectByPrimaryKey(id);
		if(blog != null){
			
			blogVo.setAuthor(blog.getAuthor());
			blogVo.setCategoryid(blog.getCategoryid());
			blogVo.setContent(blog.getContent());
			blogVo.setCreated(blog.getCreated());
			blogVo.setUpdated(blog.getUpdated());
			blogVo.setId(blog.getId());
			blogVo.setTitle(blog.getTitle());
			
			String name = catMapper.selectNameById(blog.getCategoryid());
			blogVo.setCategoryName(name);
			
		}
		detailVo.setBlogVo(blogVo);
		
		
		//设置user
		MUser user = userMapper.selectByPrimaryKey(1);
		detailVo.setUser(user);
		
		//设置目录分类
		MCategoryExample example = new MCategoryExample();
		List<MCategory> categoryList = catMapper.selectByExample(example);
		detailVo.setCaterogyList(categoryList);
		
		
		//设置上一篇的博客的名字
		
		MBlog priviousBlog = blogMapper.selectByPrimaryKey(blog.getId()-1);
		
		if(priviousBlog == null){
			detailVo.setPriviousName("没有了");
		}else{
			detailVo.setPriviousName(priviousBlog.getTitle());
		}
		
		//设置下一篇的博客的名字
		MBlog nextBlog = blogMapper.selectByPrimaryKey(blog.getId() + 1);
		
		if(nextBlog == null){
			detailVo.setNextName("没有了");
		}else{
			detailVo.setNextName(nextBlog.getTitle());
		}
		
		return detailVo;
	}


	
	//首页中 按目录分类id查询  blogVoList
	@Override
	public MBlogAndCategoryVo queryBlogByCat(Integer categoryid) {
		
		MBlogAndCategoryVo vo = new MBlogAndCategoryVo();
			
		List<MBlog> blogList = blogMapper.selectByCategoryId(categoryid);
		
		//组装、设置 blogVo
		List<MBlogVo> blogVoList = createBlogListVo(blogList);
		vo.setBlogVoList(blogVoList);
		
		
		//设置user
		MUser user = userMapper.selectByPrimaryKey(1);
		vo.setUser(user);
		
		//设置目录分类
		MCategoryExample example = new MCategoryExample();
		List<MCategory> categoryList = catMapper.selectByExample(example);
		vo.setCaterogyList(categoryList);
			
		return vo;
	}


	@Override
	public MBlogAndCategoryVo queryBlogByName(String title) {
		
		MBlogAndCategoryVo vo = new MBlogAndCategoryVo();
		List<MBlog> blogList ; 
		//如果用户没有输入title,则代表查所有的
		
		if( title == null || "".equals(title)){
			MBlogExample example = new MBlogExample();
			example.setOrderByClause("updated desc");
			
			blogList = blogMapper.selectByExampleWithBLOBs(example );
		}else{
			title = "%"+title+"%";
			blogList = blogMapper.selectByName(title);
		}
		
		//组装、设置 blogVo
		List<MBlogVo> blogVoList = createBlogListVo(blogList);
		vo.setBlogVoList(blogVoList);
		
		
		//设置user
		MUser user = userMapper.selectByPrimaryKey(1);
		vo.setUser(user);
		
		//设置目录分类
		MCategoryExample example = new MCategoryExample();
		List<MCategory> categoryList = catMapper.selectByExample(example);
		vo.setCaterogyList(categoryList);
			
		return vo;
		
	}
	
	
	
	// 打印功能开始
	@Override
	public Map printById(Integer id,String title,String link) {
		
		MBlog blog = selectById(id);
		
		//System.out.println(blog.getContent());
		
		//将 双引号 全部替换成单引号， 
		//还需要重构。 图片在本地，无法弄到pdf中。
		/*思路：
		 	将图片的链接截取出来，并且在这里吧图片真实的上传到服务器上，并且将真正的图片链接插入到img标签中。
		*/
		String content = blog.getContent();
		content = content.replaceAll("\"", "'");
		
		//System.out.println(content);
		
		createPdf(title,content,link);
		
		Map map = new HashMap();
		map.put("status", 0);
		return map;
		
	}


	private void createPdf(String title, String content,String link) {
		
		try {
			BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
			Font font = new Font(bfChinese, 16, Font.BOLD);
			Font FontChinese10 = new Font(bfChinese, 10, Font.NORMAL);
			
			//生成的新文件路径
			String newPath = "D:\\"+title+".pdf";
			
			Document document = new Document(PageSize.A4, 10, 10, 10, 10);
			PdfWriter mPdfWriter = PdfWriter.getInstance(document, new FileOutputStream(newPath));
			document.open();
			
			
			//第1个表格
		    PdfPTable table1 = new PdfPTable(1);
            PdfPCell cell11 = new PdfPCell(new Paragraph(title,font));
            cell11.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell11.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell11.setBorder(0);
            table1.addCell(cell11);
            document.add(table1);
			
            
            String realLink = "localhost:8080/index/"+ link;
            
            //第2个表格
            PdfPTable table = new PdfPTable(3);  
            
            table.setPaddingTop(60);
            table.setWidthPercentage(100);
            PdfPCell cell1 = new PdfPCell(new Paragraph("",FontChinese10));
            PdfPCell cell2 = new PdfPCell(new Paragraph("",FontChinese10));
            PdfPCell cell3 = new PdfPCell(new Paragraph("作者:安否",FontChinese10));
            PdfPCell cell4 = new PdfPCell(new Paragraph("链接:"+realLink,FontChinese10));
            
            cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell1.setBorder(0);
            cell1.setRowspan(2);
            
            cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell2.setBorder(0);
            cell2.setRowspan(2);
            
            cell3.setBorder(0);
            cell4.setBorder(0);
            
            table.addCell(cell1);
            table.addCell(cell2);
            table.addCell(cell3);
            table.addCell(cell4);
            document.add(table);
            
            //加入空行
            //Paragraph blankRow1 = new Paragraph(12f, " ", FontChinese18); 
           // System.out.println(content);
			//String s = getHtml(content);
			ByteArrayInputStream bin = new ByteArrayInputStream(content.getBytes());
			XMLWorkerHelper.getInstance().parseXHtml(mPdfWriter, document, bin, Charset.forName("UTF-8"), new ChinaFontProvide());
			
			document.close();
			mPdfWriter.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//提供中文
	public static final class ChinaFontProvide implements FontProvider {
 
		@Override
		public Font getFont(String arg0, String arg1, boolean arg2, float arg3,
				int arg4, BaseColor arg5) {
			BaseFont bfChinese = null;
			try {
				bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
						BaseFont.NOT_EMBEDDED);
			} catch (Exception e) {
				e.printStackTrace();
			}
			Font FontChinese = new Font(bfChinese, 12, Font.NORMAL);
			return FontChinese;
		}
																	
		@Override
		public boolean isRegistered(String arg0) {
			return false;
		}
	}
	 
	//打印功能结束
	

}
